<?php

namespace App\Repositories;

use App\Jobs\RetailJob;
use App\Models\Order;
use App\Models\Cart;
use App\Models\Product;
use App\Models\OrderAddress;
use App\Models\OrderProduct;
use App\Exceptions\InvalidException;
use DB;
use App\Util\Sn;
use Illuminate\Support\Facades\Redis;

class OrderRepo
{
    const ORDER_INFO_KEY = "order:info:{id}";
    public function getOrderKey($order_id):string
    {
        return str_replace('{id}',$order_id,self::ORDER_INFO_KEY);
    }
    public function createOrder($user_id,$address,$products,$beizhu="")
    {
        $total = 0;
        foreach($products as $item) {
            $total += $item['product']['price'] * $item['num'];
        }
        DB::beginTransaction();
        try{
            $orderData = [
                'user_id' => $user_id,
                'sn'  => Sn::generate(),
                'total' => $total
            ];
            $order = Order::create($orderData);
            //创建订单
            $addressData = [
                'user_id'=>$user_id,
                'name'  => $address['name'],
                'mobile' => $address['mobile'],
                'province' => $address['province'],
                'city' => $address['city'],
                'area'  =>  $address['area'],
                'detail'  =>  $address['detail'],
                'order_id'=>$order->id
            ];
            OrderAddress::create($addressData);
            $productsData = [];

            foreach ($products as $key => $item) {
                    $cartInfo = null;
                    if(!empty($item['cart_id'])) {
                        $cartInfo = Cart::where('id',$item['cart_id'])->first();
                    }

                    $productsData[] = [
                        'order_id' => $order->id,
                        'num' => $item['num'],
                        'name' => $item['product']['name'],
                        'product_id' => $item['product']['id'],
                        'user_id' => $user_id,
                        'price' => $item['product']['price'],
                        'image' => $item['product']['image'],
                        'product_sku_id' => empty($cartInfo)? empty($item['specProduct'])?0:$item['specProduct']['id']:$cartInfo->product_sku_id,
                        'spec_info'=> empty($cartInfo)? empty($item['specProduct'])?'':$item['specProduct']['spec']:$cartInfo->spec_info,
                        'spec_type' => $item['product']['spec_type'],
                    ];
                    if($cartInfo) {
                         $cartInfo->delete();
                    }

            }
            OrderProduct::insert($productsData);
            DB::commit();
        }catch(\Exception $e) {
            DB::rollBack();
            throw new InvalidException($e->getMessage());
        }
    }
    public function getOrderList($where=[],$page=15)
    {
        // var_dump($where);
        return Order::where('is_able',1)->where(function($query) use ($where){
            if(!empty($where['sn'])) {
                $query->where('sn','like',$where['sn']);
            }
            if(!empty($where['state'])){
                $query->where('state',$where['state']);
            }
            if(!empty($where['date_time'])) {
                $query->whereBetween('created_at',[$where['date_time'][0],$where['date_time'][1]]);
            }
        })->with([
        	'products'=>function($query){

        	},
            'orderAddress'=>function($query) {

            },
        	'user'=>function($query){

    	    }
    ])->orderBy('id','desc')->paginate($page)->toArray();
    }

    public function delOrder($id)
    {
        $order = Order::where('id',$id)->first();
        if(!$order) {
            throw new InvalidException("订单不存在");
        }
        try{
            $order->delete();

        } catch(\Exception $e){
            throw new InvalidException($e->getMessage());
        }
    }
    public function getOrderListsByUid($user_id=0,$where=[],$page=10)
    {
        return Order::where('is_able',1)->where('user_id',$user_id)->where(function($query) use ($where){
            if(!empty($where['state']) && $where['state'] != 0) {
                $query->where('state',$where['state']);
            }
        })->with([
            'orderProducts'=>function($query){
                $query->with(['product','specProduct']);
            }
    ])->orderBy('id','desc')->paginate($page)->toArray();
    }

    public function getOrderInfo($order_id = 0)
    {
        $keyId = $this->getOrderKey($order_id);
        //查询缓存是否有订单
        $order = Redis::hget($keyId);
        if($order) {
            return  $order;
        }
        //缓存丢失，查询数据库
        $order  =  Order::where('id',$order_id)->with([
            'orderProducts'
        ])->first();
        //订单的信息存在，放入缓存
        if($order) {
             Redis::hset($keyId,$order);
        }
        return  $order;
    }

    public function editOrder($order_id,$data)
    {
        $order = Order::where('id',$order_id)->first();
        if(!$order) {
            throw new InvalidException('订单不存在');
        }
        $order->state = $data['state'];
        $order->save();
    }

    public function setSend($order_id)
    {
        $order = Order::where('id',$order_id)->first();
        if(!$order) {
            throw new InvalidException('订单不存在');
        }
        $order->state = Order::STATUS['HAVED_SEND'];
        $order->send_time = date('Y-m-d H:i:s',time());
        $order->save();
    }
    public function setTake($order_id)
    {
        $order = Order::where('id',$order_id)->first();
        if(!$order) {
            throw new InvalidException('订单不存在');
        }
        $order->state = Order::STATUS['HAVED_Take'];
        $order->take_time = date('Y-m-d H:i:s',time());
        $order->save();
        //用户收货以后处理分销
        //2.处理分销
        RetailJob::dispatch($order);
    }
    public function getDetail($order_id)
    {
        $order = Order::where('id',$order_id)->first();
        if(!$order) {
            throw new InvalidException('订单不存在');
        }


        return Order::where('id',$order_id)->with([
            'orderProducts'=>function($query){
                $query->with(['product','specProduct']);
            },
            'orderAddress'=>function($query) {

            },
            'user'=>function($query){

            }
        ])->first();
    }
}
